package com.wuiy.util;

import android.util.JsonReader;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by WUIY on 2017/10/24.
 */

public class JSONUtils {
    public static Map<String, String> getDataMap(InputStream retVal) {
        Map<String, String> dataMap = new HashMap<String, String>();
        JsonReader jsonReader = null;
        try {
            jsonReader = new JsonReader(new InputStreamReader(retVal, "UTF-8"));
            jsonReader.beginObject();
            while (jsonReader.hasNext()) {
                String key = jsonReader.nextName();
                switch (key) {
                    case "humidity":
                        dataMap.put("humidity", jsonReader.nextInt() + "") ;
                        break;
                    case "pm2.5":
                        dataMap.put("pm2.5", jsonReader.nextInt() + "");
                        break;
                    case "co2":
                        dataMap.put("co2", jsonReader.nextInt() + "");
                        break;
                    case "LightIntensity":
                        dataMap.put("LightIntensity", jsonReader.nextInt() + "");
                        break;
                    case "temperature":
                        dataMap.put("temperature", jsonReader.nextInt() + "");
                        break;
                    default:
                        jsonReader.skipValue();
                        break;
                }
            }
            jsonReader.endObject();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                jsonReader.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return dataMap;
    }
}
